
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-switch
        v-model="fillterSwitch"
        active-color="#13ce66"
        inactive-color="#ff4949"
        style="float:right;"
      >
      </el-switch>

      <el-input
        v-model="searchInpt"
        placeholder="输入ID/昵称/手机号"
        clearable
        @keyup.enter.native="search()"
        class="search-btn"
      >
      </el-input>

      <div class="lz-tips">
        <label>用户筛选:</label>
      </div>
      <el-select
        v-model="userStatusValue"
        placeholder="用户筛选"
        @change="search()"
      >
        <el-option
          v-for="item in userStatus"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button
        type="primary"
        @click="search()"
      >
        搜索
      </el-button>
    </div>
    <div
      class="filter-container"
      v-if="fillterSwitch"
    >
      <h5>标签筛选</h5>
      <div
        v-for="(label,index) in labelSelect"
        :key="index"
        style="margin:5px 0"
      >
        <div class="lz-tips">
          <label>{{label.parenLabelName}}:</label>
        </div>
        <el-select v-model="labelTrueValue[index].conditionType">
          <el-option
            label="是"
            value="1"
          >
          </el-option>
          <el-option
            label="否"
            value="0"
          ></el-option>
        </el-select>
        <el-select
          v-model="labelValue[index]"
          multiple
          placeholder="请选择"
          @change="selectLabelChange($event, index,label.parenLabelId)"
        >
          <el-option
            v-for="option in label.childLabels"
            :key="option.childLabelId"
            :label="option.childLabelName"
            :value="option.childLabelId"
          >
          </el-option>
        </el-select>

        <el-button
          type="danger"
          @click="delSelectLabel(index)"
        >
          删除
        </el-button>
      </div>
      <el-button
        v-for="label in allLabelList"
        :key="label.parenLabelId"
        @click="addLabelSelect(label)"
      >
        {{label.parenLabelName}}
      </el-button>
    </div>
    <div
      style="text-align:center;"
      class="filter-container"
    >
    </div>
    <div class="table_container">
      <Table
        :table="dataTable"
        @handleSortChange="handleSortChange"
      >
        <template
          slot-scope="props"
          slot="hardwareEquipment"
        >
          <el-button
            type="text"
            size="small"
            @click="goUrl(props.obj.row,2)"
          >{{props.obj.row.hardwareEquipment}}</el-button>
        </template>
        <template
          slot-scope="props"
          slot="chakan"
        >
          <el-button
            @click="goUrl(props.obj.row,1)"
            type="text"
            size="small"
          >详情</el-button>

          <el-button
            @click="goUrl(props.obj.row,3)"
            type="text"
            size="small"
          >备注</el-button>

          <el-button
            @click="goUrl(props.obj.row,4)"
            type="text"
            size="small"
          >曲线</el-button>
        </template>
        <template
          slot-scope="props"
          slot="communicateWay"
        >
          <el-button
            type="text"
            @click="openChangeWay(props.obj.row)"
          >
            <div
              style="display:inline-block;"
              v-for="(item,index) in props.obj.row.communicateWay"
              :key="index"
            >
              <span v-if="item == 1">
                &nbsp;电话&nbsp;
              </span>
              <span v-if="item == 2">
                &nbsp;短信&nbsp;
              </span>
              <span v-if="item == 3">
                &nbsp;微信&nbsp;
              </span>
              <span v-if="item == 4">
                &nbsp;App推送&nbsp;
              </span>
              <span v-if="item == 0">
                &nbsp;未沟通&nbsp;
              </span>
            </div>
          </el-button>
        </template>
      </Table>
      <div
        class="Pagination"
        style="text-align: left;margin-top: 10px;"
      >
        <el-pagination
          v-if="pageshow"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="limit"
          layout="total, prev, pager, next"
          :total="count"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="修改沟通方式"
      :visible.sync="dialogChangeWay"
      width="50%"
      center
    >
      <span>
        请按照用户的真实意愿勾选下列选项：
      </span>
      <el-form
        :model="changeWayData"
        :rules="rules"
        ref="changeWayData"
      >
        <el-form-item
          :label-width="formLabelWidth"
          prop="checkbox"
        >
          <el-checkbox-group v-model="changeWayData.checkbox">
            <template v-for="checkbox in wayCheckbox">
              <el-checkbox
                :label="checkbox.label"
                :key="checkbox.label"
                name="checkbox"
                v-if="checkbox.label !== '4'"
              >{{checkbox.name}} </el-checkbox>
            </template>
            <el-checkbox
              label="4"
              name="checkbox"
              disabled
            >App推送</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogChangeWay = false">取 消</el-button>
        <el-button
          type="primary"
          @click="doChangeWay('changeWayData')"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getUserList, fetchUserCommunicate, fetchLabelList } from "@/api/table";
import Table from "@/components/Table";
import format from "date-format";
export default {
  data() {
    return {
      //用户数据
      dataTable: {
        loading: false,
        border: true,
        sortChange: "handleSortChange",
        hasOperation: false,
        tr: [
          {
            id: "1",
            label: "用户ID",
            prop: "userId",
            show: true
          },
          {
            id: "2",
            label: "用户昵称",
            prop: "nickName",
            show: true
          },
          {
            id: "3",
            label: "账号",
            width: "120",
            prop: "userName",
            show: true
          },
          {
            id: "4",
            label: "绑定设备",
            width: "130",
            prop: "hardwareEquipment",
            show: "template"
          },
          {
            id: "5",
            label: "注册时间",
            width: "130",
            sortable: true,
            prop: "createTime",
            show: true
          },
          {
            id: "6",
            label: "检测时间",
            width: "130",
            sortable: true,
            prop: "detectionTime",
            show: true
          },
          {
            id: "7",
            label: "检测次数",
            width: "110",
            sortable: true,
            prop: "detectionCount",
            show: true
          },
          {
            id: "8",
            label: "优孕次数",
            width: "110",
            sortable: true,
            prop: "ovuolaTimeCount",
            show: true
          },
          {
            id: "9",
            label: "沟通方式",
            width: "200",
            prop: "communicateWay",
            show: "template"
          },
          {
            id: "10",
            label: "查看",
            width: "150",
            prop: "chakan",
            show: "template"
          }
        ],
        data: [],
        operation: {}
      },
      //总页码
      count: 0,
      //单页行数
      limit: 20,
      //页码
      currentPage: 1,
      //搜索重置页码开关
      pageshow: true,
      //搜索
      searchInpt: "",
      searchLoading: false,
      //删选用户类型
      userStatusValue: "",
      userStatus: [
        {
          value: "",
          label: "全部"
        },
        {
          value: "0",
          label: "正式用户"
        },
        {
          value: "1",
          label: "测试用户"
        },
        {
          value: "3",
          label: "海外用户"
        }
      ],
      //标签表单
      labelRuleForm: [],
      //标签删选切换
      fillterSwitch: false,
      //全部标签
      allLabelList: [],
      //添加的标签条件列表
      labelSelect: [],
      //标签删选条件
      labelValue: [],
      //传给后台的删选条件数组
      labelTrueValue: [],
      formLabelWidth: "150px",
      //打开修改沟通方式弹窗
      dialogChangeWay: false,
      //沟通方式checkbox
      wayCheckbox: [
        {
          name: "电话",
          label: "1"
        },
        {
          name: "短信",
          label: "2"
        },
        {
          name: "微信",
          label: "3"
        },
        {
          name: "App推送",
          label: "4"
        }
      ],
      //修改沟通方式默认勾选4
      changeWayData: {
        checkbox: ["4"],
        userId: ""
      },
      sortChangeData: {
        sortKey: "",
        sortStatus: ""
      },
      //表单验证
      rules: {
        checkbox: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个",
            trigger: "change"
          }
        ]
      }
    };
  },
  created() {
    this.getUsers();
    this.getLabelList();
  },
  methods: {
    //页码事件
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUsers();
    },
    //打开修改沟通方式窗口
    openChangeWay(e) {
      const newCheck = e.communicateWay.split(",");
      if (newCheck[0] === "0") {
        this.changeWayData.checkbox = [];
        this.changeWayData.checkbox.push("4");
      } else {
        this.changeWayData.checkbox = newCheck;
      }
      this.dialogChangeWay = true;
      this.changeWayData.userId = e.userId;
    },
    handleSortChange(column) {
      let _order = "";
      this.sortChangeData.sortKey = column.prop;
      if (column.order == "descending") {
        _order = "desc";
      } else if (column.order == "ascending") {
        _order = "asc";
      } else {
        _order = "";
      }
      this.sortChangeData.sortStatus = _order;
      this.getUsers();
    },
    search() {
      this.currentPage = 1;
      this.pageshow = false;
      this.getUsers();
      this.$nextTick(() => {
        this.pageshow = true;
      });
    },
    addLabelSelect(label) {
      if (this.labelSelect.indexOf(label) == "-1") {
        this.labelSelect.push(label);
        this.labelTrueValue.push({
          conditionType: "1",
          parentId: "",
          labelId: []
        });
      }
    },
    delSelectLabel(index) {
      this.labelValue.splice(index, 1);
      this.labelSelect.splice(index, 1);
      this.labelTrueValue.splice(index, 1);
    },
    selectLabelChange(event, index, parentId) {
      this.labelTrueValue[index].parentId = parentId;
      this.labelTrueValue[index].labelId = event;
    },
    //获取全部标签
    async getLabelList() {
      const res = await fetchLabelList();
      this.allLabelList = res.data;
    },
    //获取用户数据
    async getUsers(page) {
      this.dataTable.loading = true;
      let _this = this;
      let labelData;
      if (this.fillterSwitch && this.labelTrueValue.length !== 0) {
        for (let i = 0; i < this.labelValue.length; i++) {
          if (this.labelValue[i][0] == undefined) {
            _this.$message({
              message: "标签删选不能为空",
              type: "error"
            });
            return;
            break;
          }
        }
        labelData = JSON.stringify(this.labelTrueValue);
      } else {
        labelData = "";
      }
      const Users = await getUserList({
        pageSize: this.limit,
        pageNo: this.currentPage,
        status: this.userStatusValue,
        key: this.searchInpt,
        sortKey: this.sortChangeData.sortKey,
        sortStatus: this.sortChangeData.sortStatus,
        labelConditions: labelData
      });
      this.dataTable.data = [];
      this.count = Users.data.total;
      this.dataTable.loading = false;
      Users.data.list.forEach(item => {
        const data = {};
        data.userId = item.userId;
        data.communicateWay = item.communicateWay;
        data.userName = item.userName;
        data.nickName = item.nickName;
        data.hardwareEquipment = item.hardwareEquipment;
        data.bindingTime = item.bindingTime;
        data.createTime = this.formatterTime(item.createTime);
        data.detectionTime = this.formatterTime(item.detectionTime);
        data.prePregnant = item.prePregnant;
        data.detectionCount = item.detectionCount;
        data.ovuolaTimeCount = item.ovuolaTimeCount;
        if (item.email) {
          data.userName = item.email;
        }
        this.dataTable.data.push(data);
      });
    },
    //1详情2设备3备注4新开窗口去曲线图
    goUrl(data, type) {
      if (type === 1) {
        this.$router.push({
          path: "/userManage/userList/userDetail",
          query: { t: +new Date(), type: 1, userId: data.userId }
        });
      } else if (type === 2) {
        this.$router.push({
          path: "/equipmentManage/equipmentList/equipmentHistorybind",
          query: { hardwareEquipment: data.hardwareEquipment }
        });
      } else if (type === 3) {
        this.$router.push({
          path: "/userManage/userList/userMemo",
          query: { t: +new Date(), type: 1, userId: data.userId }
        });
      } else if (type === 4) {
        const { href } = this.$router.resolve({
          path: "/userManage/userList/userChart",
          query: { t: +new Date(), type: 1, userId: data.userId }
        });
        window.open(href, "_blank");
      }
    },
    //时间格式化
    formatterTime(t) {
      if (t) {
        const newTime = format("yyyy-MM-dd hh:mm:ss", new Date(t)).split(" ");
        let time = "";
        time += newTime[0] + "\n" + newTime[1];
        return time;
      } else {
        return "";
      }
    },
    //执行修改沟通方式
    doChangeWay(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.getUserCommunicate();
        } else {
          return false;
        }
      });
    },
    //修改沟通方式
    async getUserCommunicate() {
      await fetchUserCommunicate({
        userId: this.changeWayData.userId,
        communicateId: this.changeWayData.checkbox.toString()
      });
      this.$message({
        type: "success",
        message: "修改成功!"
      });
      this.dialogChangeWay = false;
      this.getUsers();
    }
  },
  components: {
    Table
  },
  computed: {
    ...mapGetters(["permission_roles"])
  }
};
</script>
<style lang="less">
.el-table {
  .cell {
    white-space: pre-line;
  }
}
</style>
